package com.zuoban.storage.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zuoban.storage.properties.StorageProperties;
import com.zuoban.storage.service.StorageService;
import lombok.RequiredArgsConstructor;

import java.io.InputStream;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.storage.service.impl
 * @Author: zxy
 * @CreateTime: 2022-10-10
 * @Description: ...
 */
@RequiredArgsConstructor
public class AliyunStorageServiceImpl implements StorageService {

    private final StorageProperties storageProperties;


    @Override
    public String upload(InputStream inputStream, String path) {
        OSS client = new OSSClientBuilder().build(storageProperties.getAliyun().getEndPoint(),
                storageProperties.getAliyun().getAccessKeyId(), storageProperties.getAliyun().getAccessKeySecret());
        try {
            client.putObject(storageProperties.getAliyun().getBucketName(), path, inputStream);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败：", e);
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }

        return storageProperties.getConfig().getDomain() + "/" + path;
    }
}
